<template>
  <basic-container>
    <!-- <el-tabs v-model="activeName">
      <el-tab-pane label="批次追溯" name="批次追溯"> -->
    <div class="header">
      <el-form label-width="100px" :inline="true" :model="form" :rules="rules">
        <el-form-item label="物料编码:" prop="partNo">
          <el-input v-model="form.partNo" readonly placeholder="请选择物料编码">
            <el-button slot="append" icon="el-icon-search" @click="openPartModal"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="D/C:" prop="dateCode">
          <el-select v-model="form.dateCode" placeholder="请选择D/C" clearable @focus="queryDateCodeList">
            <el-option v-for="item in dateCodeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商批次:" prop="vendorLotNo">
          <el-select v-model="form.vendorLotNo" placeholder="请选择供应商批次" clearable @focus="queryVendorLotNoList">
            <el-option v-for="item in vendorLotNoList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料批次:" prop="partLot">
          <!-- <el-input v-model="form.partLot" placeholder="请输入物料批次"></el-input> -->
          <el-select v-model="form.partLot" placeholder="请选择物料批次" clearable @focus="queryLotNoList">
            <el-option v-for="item in partLotList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料品牌:" prop="partBrand">
          <el-input v-model="form.partBrand"></el-input>
        </el-form-item>
        <el-row style="text-align: right">
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" size="small" icon="el-icon-search" @click="onSubmit">查询</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-divider>基础信息</el-divider>

    <div id="partInfo" class="title">
      <div class="titleLeft">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <div class="titleName" @click="toggleMenu('isShowPartInfo')">
          <h4>物料信息</h4>
          <i :class="[isShowPartInfo ? 'arrowDown' : '']" class="arrowRight el-icon-arrow-right"></i>
        </div>
      </div>
      <span>共{{ partInfoData.length }}条记录</span>
    </div>
    <transition name="reverseTraceability">
      <avue-crud
        v-show="isShowPartInfo"
        :option="partInfoOption"
        :data="partInfoData"
        :page.sync="partInfoPage"
        @current-change="partInfoCurrentChange"
        @size-change="partInfoSizeChange"
      >
        <template slot-scope="{ row }" slot="menu">
          <el-button icon="el-icon-view" size="small" type="text" @click="partDetailView(row)">包装详情</el-button>
        </template>
      </avue-crud>
    </transition>

    <el-divider>生产信息</el-divider>

    <div id="workOrderUseInfo" class="title">
      <div class="titleLeft">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <div class="titleName" @click="toggleMenu('isShowWorkOrderUseInfo')">
          <h4>工单使用信息</h4>
          <i :class="[isShowWorkOrderUseInfo ? 'arrowDown' : '']" class="arrowRight el-icon-arrow-right"></i>
        </div>
      </div>
      <span>共{{ workOrderUseInfoData.length }}条记录</span>
    </div>
    <transition name="reverseTraceability"
      ><avue-crud
        v-show="isShowWorkOrderUseInfo"
        :option="workOrderUseInfoOption"
        :data="workOrderUseInfoData"
        :page.sync="workOrderUsePage"
        @current-change="workOrderUseCurrentChange"
        @size-change="workOrderUseSizeChange"
      >
        <template slot-scope="{ row }" slot="menu">
          <el-button icon="el-icon-view" size="small" type="text" @click="workOrderUseDetailView(row)">详情</el-button>
        </template>
      </avue-crud>
    </transition>

    <el-divider>品质信息</el-divider>
    <div id="inspectionInfo" class="title">
      <div class="titleLeft">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <div class="titleName" @click="toggleMenu('isShowInspectionInfo')">
          <h4>检验信息</h4>
          <i :class="[isShowInspectionInfo ? 'arrowDown' : '']" class="arrowRight el-icon-arrow-right"></i>
        </div>
      </div>
      <span>共{{ inspectionInfoData.length }}条记录</span>
    </div>
    <transition name="reverseTraceability">
      <avue-crud v-show="isShowInspectionInfo" :option="inspectionInfoOption" :data="inspectionInfoData">
        <template slot-scope="{ row }" slot="menu">
          <el-button icon="el-icon-view" size="small" type="text" @click="inspectionReportView(row)">{{ row.documentType === 'IQC' ? '检验报表' : '超期检验详情' }}</el-button>
        </template>
      </avue-crud>
    </transition>

    <!-- </el-tab-pane>
      <el-tab-pane label="包装条码追溯" name="包装条码追溯"></el-tab-pane>
    </el-tabs> -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <div v-if="!sideNav" class="box-card-hide" @click="sideNav = true">
      <i class="el-icon-arrow-right"></i>
    </div>
    <el-card v-if="sideNav" class="box-card">
      <div slot="header" class="clearfix">
        <span>目录</span>
        <el-button style="float: right; padding: 3px 3px" type="info" icon="el-icon-close" circle @click="sideNav = false"></el-button>
      </div>
      <div class="catalogue">
        <div>基础信息</div>
        <ul>
          <li @click="goToLocation('#partInfo')">物料信息</li>
        </ul>
        <div>生产信息</div>
        <ul>
          <li @click="goToLocation('#workOrderUseInfo')">工单使用信息</li>
        </ul>
        <div>品质信息</div>
        <ul>
          <li @click="goToLocation('#inspectionInfo')">检验信息</li>
        </ul>
      </div>
    </el-card>
    <view-over-time-wait-inspect ref="handleInspect" :visible.sync="handleVisable" @closeDialog="handleCloseBeforeInspect"></view-over-time-wait-inspect>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import {
  getTraceabilityRecord,
  getDateCodeList,
  getVendorLotNoList,
  getLotNoList,
  getPartInfo,
  getworkOrderPickingInfo,
  getworkOrderUseInfo,
  getInspectionInfo
} from '@/api/report/reverse-traceability';
import { mapGetters } from 'vuex';
import viewOverTimeWaitInspect from '@/views/quality/viewOverTimeWaitInspect';
export default {
  name: 'reverseTraceability',
  components: {
    CommonModalTemplate,
    viewOverTimeWaitInspect
  },
  mixins: [],
  data() {
    return {
      isShowPartInfo: true,
      isShowProductPickingInfo: true,
      isShowWorkOrderUseInfo: true,
      isShowInspectionInfo: false,
      sideNav: true,
      // activeName: '批次追溯',
      form: {},
      partLotList: [], //物料批次下拉数据
      rules: {
        partNo: [
          {
            required: true,
            trigger: 'submit',
            validator: (rule, value, callback) => {
              callback();
            }
          }
        ]
      },
      inspectionInfoData: [], //检验信息
      inspectionInfoOption: {
        //检验信息表格配置
        height: 300,
        calcHeight: 30,
        border: true,
        index: true,
        selection: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        refreshBtn: false,
        columnBtn: false,
        indexLabel: '序号',
        menu: true,
        column: [
          {
            label: '检验类型',
            prop: 'documentType',
            type: 'select',
            dicData: [
              { label: '来料检验', value: 'IQC' },
              { label: '超期检验', value: 'ODQC' }
            ]
          },
          {
            label: '检验单号',
            prop: 'documentNo'
          },
          {
            label: '检验人员',
            prop: 'examineBy'
          },
          {
            label: '检验时间',
            prop: 'examineDate'
          },
          {
            label: '检验结果',
            prop: 'examineResult'
          }
        ]
      },
      tableOption: {},
      timer: new Date().getTime(),
      partInfoOption: {
        height: 300,
        calcHeight: 30,
        border: true,
        index: true,
        selection: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        refreshBtn: false,
        columnBtn: false,
        indexLabel: '序号',
        menu: true,
        column: [
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '品牌',
            prop: 'partBrand'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '供应商',
            prop: 'vendorName'
          },
          {
            label: 'D/C',
            prop: 'dateCode'
          },
          {
            label: '供应商批次',
            prop: 'vendorLotNo'
          },
          {
            label: '物料批次',
            prop: 'lotNo'
          },
          {
            label: '批次数量',
            prop: 'lotQuantity'
          }
        ]
      },
      partInfoData: [],
      partInfoPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      workOrderUseInfoOption: {
        height: 300,
        calcHeight: 30,
        border: true,
        index: true,
        selection: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        refreshBtn: false,
        columnBtn: false,
        indexLabel: '序号',
        menu: true,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo'
          },
          {
            label: '产品编码',
            prop: 'productPartNo'
          },
          {
            label: '产品型号',
            prop: 'productPartModel'
          },
          {
            label: '生产批次',
            prop: 'lotNo'
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '关联产品数',
            prop: 'relatedProducts'
          }
        ]
      },
      workOrderUseInfoData: [],
      workOrderUsePage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      dateCodeList: [],
      vendorLotNoList: [],
      handleVisable: false
    };
  },
  computed: {
    ...mapGetters(['permission'])
  },
  mounted() {
    console.log(this.$route.query);
    if (JSON.stringify(this.$route.query) !== '{}') {
      if (this.$route.query.partNo) {
        this.form.partNo = this.$route.query.partNo;
      }
      if (this.$route.query.dateCode) {
        this.form.dateCode = this.$route.query.dateCode;
      }
      if (this.$route.query.vendorLotNo) {
        this.form.vendorLotNo = this.$route.query.vendorLotNo;
      }
      if (this.$route.query.partLot) {
        this.form.partLot = this.$route.query.partLot;
      }
      if (this.$route.query.partBrand) {
        this.form.partBrand = this.$route.query.partBrand;
      }
      this.onSubmit();
    }
  },
  methods: {
    openPartModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '物料数据（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=false',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '类型',
            prop: 'categoryId',
            search: true,
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '规格',
            prop: 'partSpec'
          },
          {
            label: '描述',
            prop: 'description'
          },
          {
            label: '版本',
            prop: 'revision'
          },
          {
            label: '仓库物料类别',
            prop: 'partType',
            hide: true,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type'
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      this.$set(this.form, 'partNo', this._get(rowData, 'partNo', ''));
      this.$set(this.form, 'partLot', '');
      // let params = {
      //   partMasterId: rowData.id,
      //   partMasterType: 'MATERIAL'
      // };
      this.queryDateCodeList();
      this.queryVendorLotNoList();
      this.queryLotNoList();
    },
    queryDateCodeList() {
      getDateCodeList({ partNo: this.form.partNo }).then(
        (res) => {
          this.dateCodeList = this._get(res, 'data.data', []);
        },
        (error) => {
          this.dateCodeList = [];
        }
      );
    },
    queryVendorLotNoList() {
      getVendorLotNoList({ partNo: this.form.partNo }).then(
        (res) => {
          this.vendorLotNoList = this._get(res, 'data.data', []);
        },
        (error) => {
          this.vendorLotNoList = [];
        }
      );
    },
    queryLotNoList() {
      getLotNoList({ partNo: this.form.partNo }).then(
        (res) => {
          this.partLotList = this._get(res, 'data.data', []);
        },
        (error) => {
          this.partLotList = [];
        }
      );
    },
    onSubmit() {
      if (!this.form.partNo) {
        this.$message({
          type: 'warning',
          message: '请选择物料编码！'
        });
        return;
      }
      let obj = {
        partNo: this.form.partNo,
        dateCode: this.form.dateCode,
        vendorLotNo: this.form.vendorLotNo,
        lotNo: this.form.partLot,
        partBrand: this.form.partBrand
      };
      getPartInfo(obj).then(
        (res) => {
          const data = res.data.data;
          this.partInfoPage.total = data.total;
          this.partInfoData = data.records;
        },
        (error) => {
          this.partInfoData = [];
        }
      );
      getworkOrderUseInfo(this.workOrderUsePage.currentPage, this.workOrderUsePage.pageSize, Object.assign(obj)).then(
        (res) => {
          const data = res.data.data;
          this.workOrderUsePage.total = data.total;
          this.workOrderUseInfoData = data.records;
        },
        (error) => {
          this.workOrderUseInfoData = [];
        }
      );
    },
    partInfoCurrentChange(currentPage) {
      this.productPickingInfoPage.currentPage = currentPage;
    },
    partInfoSizeChange(pageSize) {
      this.productPickingInfoPage.pageSize = pageSize;
    },
    /**
     * 页面内定位表格
     */
    goToLocation(type) {
      switch (type) {
        case '#partInfo':
          this.isShowBatchPackIdInfo = true;
          break;
        case '#workOrderUseInfo':
          this.isShowProductionPickingInfo = true;
          break;
        case '#inspectionInfo':
          this.isShowInspectionInfo = true;
          break;
        default:
          break;
      }
      console.log($(type).offset());
      console.log($(type).scrollTop + $('#avue-view').scrollTop());
      $('#avue-view').animate(
        {
          scrollTop: $(type).offset().top + $('#avue-view').scrollTop() - 110
        },
        500
      );
    },
    toggleMenu(type) {
      if (!this.form.partNo) {
        this.$message.error('请先选择物料编码');
        return;
      }
      this[type] = !this[type];
      let obj = {
        partNo: this.form.partNo,
        dateCode: this.form.dateCode,
        vendorLotNo: this.form.vendorLotNo,
        lotNo: this.form.partLot,
        partBrand: this.form.partBrand
      };
      switch (type) {
        case 'isShowInspectionInfo':
          if (this[type]) {
            getInspectionInfo(obj).then(
              (res) => {
                this.inspectionInfoData = this._get(res, 'data.data', []);
              },
              (error) => {
                this.inspectionInfoData = [];
              }
            );
          }
          break;
        default:
          break;
      }
    },
    partDetailView(row) {
      this.$refs.commonModalTemplate.showModal();
      let url = `/api/mes-product/reverse-trace/material-info/multi-condition-query/detail-page?partNo=${row.partNo}`;
      if (row.partBrand) {
        url += `&partBrand=${row.partBrand}`;
      }
      if (row.vendorName) {
        url += `&vendorName=${row.vendorName}`;
      }
      if (row.dateCode) {
        url += `&dateCode=${row.dateCode}`;
      }
      if (row.vendorLotNo) {
        url += `&vendorLotNo=${row.vendorLotNo}`;
      }
      if (row.lotNo) {
        let lotNo = row.lotNo.replace(/\|/g, ',');
        url += `&lotNos=${lotNo}`;
      }
      this.tableOption = {
        modalTitle: '详情',
        url: url,
        isPage: true,
        menu: false,
        editBtn: false,
        selection: false,
        readonly: true,
        tip: false,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '物料批次',
            prop: 'lotNo'
          },
          {
            label: '品牌',
            prop: 'partBrand'
          },
          {
            label: '供应商',
            prop: 'vendorName'
          },
          {
            label: '包装条码',
            prop: 'packSn'
          },
          {
            label: '包装数量',
            prop: 'packQuantity'
          }
        ]
      };
    },
    workOrderUseDetailView(row) {
      this.$refs.commonModalTemplate.showModal();
      let url = `/api/mes-product/reverse-trace/work-order-usage-info/detail-page?workOrderNo=${row.workOrderNo}&partNo=${this.form.partNo}`;
      this.tableOption = {
        modalTitle: '详情',
        url: url,
        isPage: true,
        menu: false,
        editBtn: false,
        selection: false,
        readonly: true,
        tip: false,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '序列号',
            prop: 'productSn',
            search: true
          }
        ]
      };
    },
    productPickingInfoCurrentChange(currentPage) {
      this.productPickingInfoPage.currentPage = currentPage;
    },
    productPickingInfoSizeChange(pageSize) {
      this.productPickingInfoPage.pageSize = pageSize;
    },
    goSheetNoPage(sheetNo) {
      this.$router.push({
        path: '/warehouse/productrefactor/materialRequisition',
        query: { sheetNo: sheetNo }
      });
    },
    inspectionReportView(row) {
      if (row.documentType === 'IQC') {
        window.open(`${this.website.reportUrl}/preview?_u=blade-ZRY-IQC检验报告.ureport.xml&qcId=${row.documentId}`);
      } else {
        this.$refs.handleInspect.getData(row.documentId);
        this.handleVisable = true;
      }
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>
<style lang="scss" scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.title {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0;
  align-items: center;
  height: 35px;
  .titleLeft {
    display: flex;
    align-items: center;
    .titleName {
      user-select: none;
      display: flex;
      align-items: center;
      cursor: pointer;
      .arrowRight {
        transform: rotate(0);
        transition: all 0.2s;
        &.arrowDown {
          transform: rotate(90deg);
          transition: all 0.2s;
        }
      }
    }
  }
  span {
    color: #0995bb;
  }
}
::v-deep .el-card__body {
  padding: 20px;
  .avue-crud__menu {
    display: none;
  }
}
::v-deep .el-table {
  margin-bottom: 25px;
}
.box-card {
  position: absolute;
  top: 50%;
  right: 1%;
  width: 11%;
  min-width: 200px;
  translate: 0 -50%;
  // height: 70%;
  z-index: 9999;
  .catalogue {
    user-select: none;
    ul {
      margin-left: -10px;
      li {
        list-style: disc;
        line-height: 25px;
        cursor: pointer;
      }
    }
  }
}
.box-card-hide {
  position: absolute;
  top: 30%;
  right: 1%;
  width: 50px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  vertical-align: middle;
  background-color: #ffffff;
  border: 1px solid #ebeef5;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  cursor: pointer;
  z-index: 9999;
}
::v-deep .el-form-item__content {
  line-height: 32px;
}

.reverseTraceability-enter-active,
.reverseTraceability-leave-active {
  transition: opacity 0.2s;
}
.reverseTraceability-enter,
.reverseTraceability-leave-to {
  opacity: 0;
}
::v-deep .is-never-shadow {
  padding: 0;
}
::v-deep .avue-crud--card {
  .el-card__body {
    padding: 0;
  }
}
</style>
